<template>
  <!--订单-->
  <div class="container-box">
    <div class="cart-box" v-show="!orderDetailVisible">
      <el-card v-if="!showProductDetail" style="width: 80%">
        <el-row class="flex-center">
          <h3>我的订单</h3>
        </el-row>

        <el-row>
          <div class="address-container">
            <!-- （未支付1、已支付2、已发货3、已完成4、已退款5、已取消6） -->
            <el-tabs v-model="activeStatus" @tab-click="handleTabClick">
              <el-tab-pane
                v-for="(item, index) in statusList"
                :key="index"
                :label="item.label"
                :name="item.value"
              >
                <!-- 订单表格 -->
                <el-table
                  default-expand-all
                  :border="true"
                  :data="orderList"
                  tooltip-effect="dark"
                  style="width: 100%"
                >
                  <!-- 展开 -->
                  <el-table-column type="expand">
                    <template slot-scope="props">
                      <div class="address-container">
                        <el-table
                          :border="true"
                          ref="multipleTable"
                          :data="props.row.orderdetailsList"
                          tooltip-effect="dark"
                          style="width: 100%"
                        >
                          <el-table-column
                            align="center"
                            label="商品主图"
                            prop="pictures"
                            width="120"
                          >
                            <template v-slot="{ row }">
                              <img
                                :src="JSON.parse(row.pictures)[0]"
                                alt
                                style="
                                  width: 80px;
                                  height: auto;
                                  cursor: pointer;
                                "
                              />
                            </template>
                          </el-table-column>
                          <el-table-column
                            align="center"
                            label="商品名称"
                            prop="product_name"
                            width="120"
                          ></el-table-column>
                          <el-table-column
                            align="center"
                            prop="category_name"
                            label="商品分类"
                            width="120"
                          ></el-table-column>
                          <el-table-column
                            align="center"
                            prop="product_description"
                            label="商品描述"
                          ></el-table-column>
                          <el-table-column
                            align="center"
                            prop="stock"
                            label="库存(件)"
                            width="120"
                          ></el-table-column>

                          <el-table-column
                            align="center"
                            width="160"
                            prop="quantity"
                            label="商品数量"
                          ></el-table-column>
                          <el-table-column
                            align="center"
                            prop="price"
                            label="价格(元)"
                          ></el-table-column>
                          <el-table-column
                            align="center"
                            prop="price"
                            label="金额(元)"
                          >
                            <template v-slot="{ row }">{{
                              parseFloat(row.price * row.quantity).toFixed(2)
                            }}</template>
                          </el-table-column>
                        </el-table>
                      </div>
                    </template>
                  </el-table-column>

                  <!-- 展开 -->
                  <el-table-column
                    align="center"
                    label="序号"
                    type="index"
                    width="55"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    label="收货人"
                    prop="recipient_name"
                    width="120"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="recipient_phone"
                    label="收货号码"
                    width="120"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="address"
                    label="收货地址"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="created_at"
                    label="订单创建时间"
                    width="160"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    prop="updated_at"
                    label="订单更新时间"
                    width="160"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    width="100"
                    prop="total_amount"
                    label="总金额"
                  ></el-table-column>
                  <el-table-column
                    v-if="!['4', '5', '6'].includes(activeStatus)"
                    align="center"
                    width="140"
                    label="操作"
                  >
                    <template v-slot="{ row }">
                      <el-link
                        v-if="+row.status == 1"
                        style="margin-left: 10px"
                        :underline="false"
                        type="primary"
                        @click="toPay(row)"
                        >支付</el-link
                      >
                      <el-link
                        v-if="+row.status == 2"
                        style="margin-left: 10px"
                        :underline="false"
                        type="primary"
                        @click="toRefund(row)"
                        >退款</el-link
                      >

                      <el-link
                        v-if="+row.status == 3"
                        style="margin-left: 10px"
                        :underline="false"
                        type="primary"
                        @click="toConfirm(row)"
                        >确认收货</el-link
                      >

                      <el-link
                        v-if="row.status == 1"
                        style="margin-left: 10px"
                        :underline="false"
                        type="danger"
                        title="取消订单"
                        @click="cancelOrder(row)"
                        >取消</el-link
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import { generateTextAvatar } from "@/utils/generateTextAvatar";
// import AddDialog from "./components/AddDialog";
import {
  getAllOrdersByUserId,
  getAllOrderdetailsByOrderId,
  updateCart,
  updateOrders,
  getInfo,
  updateInfo,
} from "@/api/user";
import ProductDetail from "@/views/productDetail/index.vue";
// import OrderDetail from "./components/OrderDetail.vue"
export default {
  components: {
    ProductDetail,
    // OrderDetail
  },
  data() {
    return {
      activeStatus: "1",
      //（未支付1、已支付2、已发货3、已完成4、已退款5、已取消6）
      statusList: [
        {
          label: "未支付",
          value: "1",
        },
        {
          label: "已支付",
          value: "2",
        },
        {
          label: "已发货",
          value: "3",
        },
        {
          label: "已完成",
          value: "4",
        },
        {
          label: "已退款",
          value: "5",
        },
        {
          label: "已取消",
          value: "6",
        },
      ],
      userInfo: null,
      orderList: [],
      multipleSelection: [],
      total: 0,
      orderDetailVisible: false,
      showProductDetail: false,

      addVisible: false,
      title: "新增地址",
      storeForm: {},
    };
  },
  computed: {
    ...mapState("user", ["token"]),
    ...mapGetters(["sidebar", "avatar", "name"]),
  },
  mounted() {
    if (!this.token) {
      this.$message.warning("请先登录,登录后再查看订单，1s后跳转到登录页！");
      return setTimeout(() => {
        this.$router.push("/login");
      }, 1000);
    }

    this.getInfo();
    this.getAllOrdersByUserId();
  },
  methods: {
    async getInfo() {
      const { data: res } = await getInfo(+this.token);
      console.log("获取用户信息成功", res);
      this.userInfo = res || {};
    },
    updateOrders(order_id, status = 6, message = "确认取消订单吗？") {
      return new Promise((resolve) => {
        this.$confirm(`${message} 是否继续?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const params = {
              order_id,
              status,
            };
            const res = await updateOrders(params);
            if (res.status === 0) {
              this.$message({
                type: "success",
                message: "操作成功",
              });
              this.getAllOrdersByUserId();
              resolve(true);
            } else {
              this.$message.error("操作失败！");
              resolve(false);
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
            resolve(false);
          });
      });
    },
    async toPay(row) {
      if (row.total_amount > this.userInfo.money) {
        return this.$message.warning("余额不足，请先充值");
      }

      this.$confirm("确认支付吗？ 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const data = {
          order_id: row.order_id,
          status: 2,
        };
        const res = await updateOrders(data);
        if (res.status === 0) {
          //更新用户余额
          await updateInfo({
            user_id: +this.token,
            money: this.userInfo.money - +row.total_amount,
          });
          this.$message({
            type: "success",
            message: "支付成功!",
          });
          this.getAllOrdersByUserId();
        } else {
          this.$message.error("支付失败！");
        }
      });
    },
    async toRefund(row) {
      // 退款
      const flag = await this.updateOrders(row.order_id, 5, "确认退款吗？");
      if (flag) {
        //退款成功，修改个人余额
        const res = await updateInfo({
          user_id: +this.token,
          money: this.userInfo.money + +row.total_amount,
        });
        if (res.status == 0) {
          this.$message({
            type: "success",
            message: "退款成功,可在充值界面查看余额",
          });
        } else {
          this.$message.error("退款失败！");
        }
      } else {
        this.$message.warning("退款失败，请稍后重试");
      }
    },
    //取消订单
    cancelOrder(row) {
      this.updateOrders(row.order_id, 6, "确认取消订单吗？");
    },
    //确认收货
    toConfirm(row) {
      this.updateOrders(row.order_id, 4, "确认收货吗？");
    },

    handleTabClick() {
      this.getAllOrdersByUserId();
    },
    // gotoDetail(row) {
    //   console.log(row);
    //   this.showProductDetail = true
    //   this.productInfo = row
    // },
    async handleQuantityChange(val, row) {
      const params = {
        cart_id: row.cart_id,
        quantity: +val,
      };
      const res = await updateCart(params);
      if (res.status === 0) {
        this.$message({
          type: "success",
          message: "修改成功",
        });
        this.getAllOrdersByUserId();
      } else {
        this.$message.error("修改失败！");
      }
    },
    toBuy() {
      if (this.multipleSelection.length === 0)
        return this.$message.warning("请选择商品");
      this.orderDetailVisible = true;
    },
    async goback() {
      await this.getAllOrdersByUserId();

      this.orderDetailVisible = false;
    },

    async changeDefault(row) {
      this.$confirm("确认设置该地址为默认地址吗？ 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const params = {
            cart_id: row.cart_id,
            user_id: +this.token,
            is_default: 1,
          };
          const res = await updateCart(params);
          if (res.status === 0) {
            this.$message({
              type: "success",
              message: "修改默认地址成功",
            });
            this.getAllOrdersByUserId();
          } else {
            this.$message.error("修改失败！");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async getAllOrdersByUserId() {
      if (!this.token) {
        this.$message.warning("请先登录！");
        return this.$router.push("/login");
      }
      const params = {
        user_id: +this.token,
        status: +this.activeStatus,
      };
      const { data: res } = await getAllOrdersByUserId(params);

      // 使用 Promise.all 等待所有异步操作完成
      this.orderList =
        (await Promise.all(
          res.map(async (item) => {
            const { data: orderDetails } = await getAllOrderdetailsByOrderId(
              item.order_id
            );
            item.orderdetailsList = orderDetails;
            return item;
          })
        )) || [];

      console.log(this.orderList);
    },

    // addAddress() {
    //   this.title = "新增地址";
    //   this.addVisible = true;
    //   this.storeForm = {};
    // },
    edit(row) {
      this.title = "修改地址";
      this.addVisible = true;
      this.storeForm = row;
    },
    addStoreConfirm() {
      //刷新列表
      this.getAllOrdersByUserId();
    },
  },
};
</script>

<style scoped lang="scss">
.cart-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 50px;

  .el-card {
    padding: 20px;

    .flex-center {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
    }
  }
}

.btn-list {
  display: flex;
  justify-content: center;

  .el-button {
    width: 200px;
  }
}

.product-detail {
  background-color: #fff;
}

.total-price {
  padding: 20px 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-right: 20px;

  .total {
    margin-right: 20px;

    .price {
      color: red;
      font-size: 20px;
    }
  }
}
</style>
